package com.szly.phm.common.utils;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HandleUtils {

    public static String UUID32() {
        var str = UUID.randomUUID().toString();
        return str.replace("-", "").trim();
    }

    /**
     * 判断手机号码的格式是否正确
     *
     * @author chengjiang
     * @date 2020/9/11
     */
    public static boolean isMobile(String mobiles) {
        Pattern p = Pattern.compile("(^1[3456789]\\d{9}$)|(^4\\d{9}$)|(^8\\d{7,9}$)|(^9\\d{4}$)");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 随机生成32位的字符串
     *
     * @auther: chengjiang
     * @date 2020/9/11
     */
    public static String getRandomString(int length) {
        int count = 0;
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < length) {
            int i = Math.abs(r.nextInt(66));
            if ((i >= 0) && (i < str.length)) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }

    /**
     * 生成纯数字字符串
     *
     * @auther: chengjiang
     * @date 2020/9/11
     */
    public static String getRandomNumber(int len) {
        int count = 0;
        char[] str = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < len) {
            int i = Math.abs(r.nextInt(10));
            if ((i >= 0) && (i < str.length)) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();
    }

    /**
     * 获取 Date 日期部分
     *
     * @param date 传入日期.
     * @return a Date 时间部分为 00:00:00.
     */
    public static Date getStartDate(Date date) {
        var c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * 获取结束时间（23:59:59）
     *
     * @author chengjiang
     * @date 2020/10/16
     */
    public static Date getEndDate(Date date) {
        date = getStartDate(date);
        var c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, 1);
        c.set(Calendar.MILLISECOND, -1);
        return c.getTime();
    }

    /**
     * 添加月
     *
     * @param date  new Date
     * @param month
     * @return
     */
    public static Date addMonth(Date date, int month) {
        var c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, month);
        return c.getTime();
    }

    public static Date addHour(Date date, int hour) {
        var c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR, hour);
        return c.getTime();
    }

    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    public static int getDay(Date date) {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    public static boolean equalDay(Date date1, Date date2) {
        return getYear(date1) == getYear(date2)
                && getMonth(date1) == getMonth(date2)
                && getDay(date1) == getDay(date2);
    }

    /**
     * 生产随机密码,字符可能由大写字母、小写字母、数字和特殊符号组成
     *
     * @author chengjiang
     * @date 2021/4/13
     */
    private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";

    public static String randomPassword(int n) {
        char[] chars = new char[n];
        Random rnd = new Random();
        for (int i = 0; i < 8; i++) {
            chars[i] = nextChar(rnd);
        }
        return new String(chars);
    }

    private static char nextChar(Random rnd) {
        switch (rnd.nextInt(4)) {
            case 0:
                return (char) ('a' + rnd.nextInt(26));
            case 1:
                return (char) ('A' + rnd.nextInt(26));
            case 2:
                return (char) ('0' + rnd.nextInt(10));
            default:
                return SPECIAL_CHARS.charAt(rnd.nextInt(SPECIAL_CHARS.length()));
        }
    }

    /**
     * 获取时间段内的天数
     *
     * @author chengjiang
     * @date 2021/4/28
     */
    public static List<String> getEveryDayConstant(Date startTime, Date endTime) {
        var sdf = new SimpleDateFormat("yyyy-MM-dd");
        var list = new ArrayList<String>();
        list.add(sdf.format(startTime));
        var calBegin = Calendar.getInstance();
        calBegin.setTime(startTime);
//        endTime = DateUtils.getDate(endTime);
        while (endTime.after(calBegin.getTime())) {
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            list.add(sdf.format(calBegin.getTime()));
        }
        return list;
    }

    /**
     *获取月份
     * @author chengjiang
     * @date 2021/5/6
     */
    public static List<String> getEveryMonthConstant(Date time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year = sdf.format(time);
        List<String> list = new ArrayList<>();
        String yearMonth = "";
        for (int i = 1; i <= 12; i++) {
            if (i >= 10) {
                yearMonth = year + "-" + i;
            } else {
                yearMonth = year + "-0" + i;
            }
            list.add(yearMonth);
        }
        return list;
    }
    /**
     *倒退12个月
     * @author ly
     * @date 2021/8/11
     */
    public static List<String> getBackEveryMonth(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year = sdf.format(time);
        List<String> list = new ArrayList<>();
        String yearMonth = "";
        Date time1 =DateUtils.addMonth(time,-11);
        for (int i = 1; i <= 12; i++) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
            String month = sdf1.format(time1);
             yearMonth = year+ "-" + month;
            list.add(yearMonth);
            time1 =DateUtils.addMonth(time1,1);
            time1=time1;
        }
        return list;
    }

    public static List<String> getMonthBetween(String minDate, String maxDate){
        ArrayList<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取小程序电话号码
     *
     * @author chengjiang
     * @date 2021/4/29
     */
    public static String getPhoneNumber(String encryptedData, String session_key, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.getDecoder().decode(session_key);
        // 偏移量
        byte[] ivByte = Base64.getDecoder().decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @ Description   :  判断list是否为空
     * @ Author        :  chengjiang
     * @ Date          :  2021/3/19
     */
    public static Boolean ListIsNotNull(List<?> list) {
        return list != null && !list.isEmpty();
    }

    /**
     * @ Description   :  判断字数是否超过限制
     * @ Author        :  chengjiang
     * @ Date          :  2021/5/8
     */
    public static boolean wordCountLimit(String columnName, int limit) {
        return columnName.length() <= limit;
    }

    /**
     * 月份阿拉伯数字转中文
     * @author chengjiang
     * @date 2021/7/12
     */
    public static String transformData(String numStr) {
        switch (numStr) {
            case "01":
                return "一";
            case "02":
                return "二";
            case "03":
                return "三";
            case "04":
                return "四";
            case "05":
                return "五";
            case "06":
                return "六";
            case "07":
                return "七";
            case "08":
                return "八";
            case "09":
                return "九";
            case "10":
                return "十";
            case "11":
                return "十一";
            case "12":
                return "十二";
            default:
                return "";
        }
    }
}
